<template>
  <el-select
    ref="selectTree"
    :clearable="DefaultClear"
    v-model="value"
    placeholder="请选择"
  >
    <el-option style="height: auto; width: auto">
      <el-tree
        :data="parentData"
        :props="defaultProps"
        @node-click="handleNodeClick"
      ></el-tree>
    </el-option>
  </el-select>
</template>

<script>
export default {
  /**
   * DefaultParentData 初始化数据列表
   * DefaultData 要查找的初始化数据
   */
  props: ["DefaultParentData", "DefaultData", "DefaultClear"],
  data() {
    return {
      defaultProps: {
        children: "children",
        label: "categoryName",
      },
      parentData: [],
      value: "",
    };
  },
  created() {    
    this.parentData = this.DefaultParentData;
    if (this.DefaultData) {
      var data = this.getDataById(
        this.parentData,
        "categorySn",
        this.DefaultData
      );
      if (data) {
        this.value = data.categoryName;
      } else {
        this.value = "";
      }
    } else {
      this.value = "";
    }
  },
  methods: {
    //根据指定的id查询树状结构里的数据
    getDataById(list, id, data) {
      //判断list是否是数组
      if (!list instanceof Array) {
        return null;
      }
      //遍历数组
      for (let i in list) {
        let item = list[i];
        if (item[id] === data) {
          return item;
        } else {
          //查不到继续遍历
          if (item.children && item.children.length > 0) {
            let value = this.getDataById(item.children, id, data);
            //查询到直接返回
            if (value) {
              return value;
            }
          }
        }
      }
    },
    handleNodeClick(data, node) {
      this.value = data.categoryName;
      //点击后关闭下拉框
      this.$refs.selectTree.blur();
      this.$emit("changeData", data);
    },
  },
};
</script>

<style scoped>
</style>

